package com.ruoyi.framework.web.service.proxy;

import com.anji.captcha.model.common.ResponseModel;
import com.anji.captcha.model.vo.CaptchaVO;
import com.anji.captcha.service.CaptchaService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.CaptchaType;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;

/**
 * @author ab785
 * createTime: 2021-10-22.
 * description: 用户名密码登录设置
 */
public class UserNameLoginFlow extends LoginFlow {

    @Override
    void checkCaptcha(LoginBody loginBody) {
        //执行校验
        boolean captchaOnOff = SpringUtils.getBean(ISysConfigService.class).selectCaptchaOnOff();
        // 验证码开关
        if (captchaOnOff) {
            String captchaType = RuoYiConfig.getCaptchaType();
            if (captchaType.equals(CaptchaType.MATH.getValue()) || captchaType.equals(CaptchaType.CHAR.getValue())) {
                //图片验证================================================
                String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + loginBody.getUuid();
                checkRedisCapture(loginBody, verifyKey);
            } else if (captchaType.equals(CaptchaType.CLICK_WORD.getValue()) || captchaType.equals(CaptchaType.BLOCK_PUZZLE.getValue())) {
                //滑块验证 ================================================
                CaptchaVO captchaVO = new CaptchaVO();
                captchaVO.setCaptchaVerification(loginBody.getCode());
                captchaVO.setCaptchaType(captchaType);
                ResponseModel response = SpringUtils.getBean(CaptchaService.class).verification(captchaVO);
                if (!response.isSuccess()) {
                    throw new CaptchaException();
                }
            }
        }
    }


    @Override
    Authentication doLogin(LoginBody loginBody) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginBody.getUsername(), loginBody.getPassword());
        AuthenticationContextHolder.setContext(authenticationToken);
        return SpringUtils.getBean(AuthenticationManager.class).authenticate(authenticationToken);
    }


    @Override
    protected void onLoginSuccess(LoginUser loginUser) {
        super.onLoginSuccess(loginUser);
        System.out.println("===》》》用户名密码登录完成回调");
    }
}
